package com.example.demo.mp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mp.entity.ShortUrl;
import com.example.demo.mp.mapper.ShortUrlMapper;
import com.example.demo.mp.service.ShortUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * (Userinfo)表服务接口
 *
 * @author makejava
 * @since 2024-12-14 15:58:05
 */
@Service
@Slf4j
public class ShortUrlServiceImpl extends ServiceImpl<ShortUrlMapper, ShortUrl> implements ShortUrlService {

    @Override
    @Cacheable(value = "shortUrlByName:", key = "#shortName")
    public ShortUrl getShortUrl(String shortName) {
        ShortUrl shortUrl = lambdaQuery().eq(ShortUrl::getShortName, shortName).one();
        if (shortUrl == null) {
            throw new RuntimeException("短链接不存在");
        }
        return shortUrl;
    }

    @Override
    public ShortUrl createShortUrl(String url) {
        String urlMd5 = SecureUtil.md5(url);
        if (checkUrl(urlMd5)) {
            throw new RuntimeException("url已存在");
        }
        ShortUrl shortUrl = new ShortUrl();
        shortUrl.setUrl(url);
        shortUrl.setUrlMd5(urlMd5);
        shortUrl.setClickCount(0L);
        shortUrl.setCreatTime(new Date());
        shortUrl.setShortName(IdUtil.nanoId(4));
        save(shortUrl);
        return shortUrl;

    }

    //检查url是否已经存在
    private Boolean checkUrl(String urlMd5) {
        List<ShortUrl> checkUrl = lambdaQuery().eq(ShortUrl::getUrlMd5, urlMd5).list();
        return CollUtil.isNotEmpty(checkUrl);
    }

    @Override
    public Boolean addClickCount(String shortName) {
        return lambdaUpdate()
                .eq(ShortUrl::getShortName, shortName)
                .setSql("click_count = click_count + 1")
                .update();
    }
}

